package cloud.mbase.controller;

import cloud.mbase.business.interf.UserBusinessInterface;
import cloud.mbase.entity.Result;
import cloud.mbase.entity.datavo.Resource;
import cloud.mbase.util.ResourceNotFoundException;
import cloud.mbase.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/base/resource")
public class ResourceController {
    @Autowired
    private UserBusinessInterface userBusiness;
    @RequestMapping(value = "/",method = RequestMethod.GET)
    public Result list(){
        List<Resource> list = userBusiness.findAllResource();
        return ResultUtil.getSuccessResult(list);
    }
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public Result getResultById(@PathVariable Integer id){
        Resource resource = userBusiness.getResourceById(id);
        if(resource == null){
            throw new ResourceNotFoundException();
        }
        return ResultUtil.getSuccessResult(resource);
    }
    @RequestMapping(value = "/",method = RequestMethod.POST)
    public Result addResource(@RequestBody Resource resource){
        Resource responseResource = userBusiness.saveResource(resource);
        return ResultUtil.getSuccessResult(responseResource);
    }
    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public Result deleteResource(@PathVariable Integer id){
        userBusiness.deleteResource(id);
        return ResultUtil.getSuccessResult();
    }
}
